<?php

namespace App\Console\Commands\WorkOrder;

use App\Models\WorkOrder\WorkOrderProductCompanyModel;
use Illuminate\Console\Command;
use GuzzleHttp\Client;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class ImportProductCompany extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workOrder:import-product-company';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入订货商品JDE code与生产厂家的映射关系';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址 : ');

        if (!$url) {
            $url = 'https://file.51kuafu.com/55/58/341c5e2fe723f021090fc9d97e5cb6a24a19c514f3a133bbdb9f2346a779.xlsx';
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.', $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        Excel::import(new ImportProductCompanyToCollection(), $savePath);

        // 删除文件
        @unlink($savePath);
    }
}

class ImportProductCompanyToCollection implements ToCollection
{
    private string $errMsg = '';

    public function collection(Collection $collection)
    {
        // 校验列名
        $this->checkHeader($collection->first());
        if ($this->errMsg) {
            dd($this->errMsg);
        }

        $data = [];
        $collection->each(function ($item, $row) use (&$data){
            $row = $row + 1;

            if ($row == 1) {
                return null;
            }
            // 常规内容校验
            list($jdeCode, $goodsName, $company) = $item;
            if (!mb_strlen($jdeCode) || !mb_strlen($goodsName) || !mb_strlen($company)) {
                dump('JDE code:' . $jdeCode . ' 商品名:' . $goodsName . ' 生产厂家:' . $company . '  信息不全  ' . '行数:' . $row);
            }
            $data[] = [
                'goodsCode' => $jdeCode,
                'goodsName' => $goodsName,
                'company'   => $company,
                'createdAt' => time(),
                'updatedAt' => time(),
            ];
            dump('JDE code:' . $jdeCode . ' 商品名:' . $goodsName . ' 生产厂家:' . $company . '读取成功');
        });
        WorkOrderProductCompanyModel::query()->insert($data);
    }

    private function checkHeader(Collection $item)
    {
        $formColumn = [
            "商品JDE编码",
            "名称（订货系统显示）",
            "厂家信息",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $item[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }
    }

}
